package ooo.reindeer.springboot.starter.cedf;

import ooo.reindeer.logging.ILogger;
import ooo.reindeer.logging.LogUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContext implements ApplicationContextAware{

    private static final ILogger logger = LogUtil.getLogger(SpringContext.class);

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        if(SpringContext.applicationContext == null) {
            SpringContext.applicationContext = applicationContext;
        }
        logger.info("application context success");
    }


    private static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T>T createBean(Class<T> clazz){
        return SpringContext.getApplicationContext().getAutowireCapableBeanFactory().createBean(clazz);
    }

    public static <T> T getBean(String name){
        return (T)getApplicationContext().getBean(name);
    }


    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }


    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }

    public static <T> T getProperty(String name,Class<T> clazz,T def){
        return getApplicationContext().getEnvironment().getProperty(name,clazz,def);
    }
}